package weibo;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import user.UserSession;
import utils.JsonOut;
import utils.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "UploadImageServlet")
public class UploadImageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String email = UserSession.getUserSessionEmail(session);
        PrintWriter out = response.getWriter();
        if (email == null || email.isEmpty()){
            out.println(JsonOut.error(220, "not_login"));
            return;
        }

        //为解析类提供配置信息
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建解析类的实例
        ServletFileUpload sfu = new ServletFileUpload(factory);
        //开始解析
        sfu.setFileSizeMax(1024*1024*4);
        sfu.setSizeMax(1024*1024*5);
        //每个表单域中数据会封装到一个对应的FileItem对象上
        try {
            List<FileItem> items = sfu.parseRequest(request);
            FileItem item = items.get(0);
            //isFormField为true，表示这不是文件上传表单域
            if(!item.isFormField()){
                String path = "/usr/local/tomcat8/webapps/ROOT/img/uploads";

                // 时间戳做文件名
                String filenameOrigin = item.getName();
                String[] filenameCompo = filenameOrigin.split("\\.");
                String fileType = filenameCompo[filenameCompo.length-1];
                if (!fileType.equals("jpg") && !fileType.equals("jpeg") && !fileType.equals("png") && !fileType.equals("gif")){
                    out.println(JsonOut.error(202, "bad_file_type"));
                    return;
                }
                String fileTime = System.currentTimeMillis() + "";
                String fileName = fileTime + "." + fileType;
                File file = new File(path+"/"+fileName);
                if(!file.exists()){
                    item.write(file);
                    //将上传图片的名字记录到数据库中
                    out.println(JsonOut.common(0, "success", fileName));
                }
            }else {
                out.println(JsonOut.error(201, "no_file0_input"));
            }
        } catch (FileUploadBase.FileSizeLimitExceededException e){
            out.println(JsonOut.error(202, "file_size_too_large"));
        } catch (Exception e) {
            e.printStackTrace();
            out.println(JsonOut.error(500, "file_error"));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(JsonOut.error(403, "forbidden"));
    }
}
